package FriendTable.Gui;
/*
更新A
 */

import FriendTable.Friend;
import FriendTable.FriendDAO;
import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class FriendGUI {
    private JFrame frame;
    private JTabbedPane tabbedPane;
    private static MainPanel mainPanel;

    public FriendGUI() {
        initializeComponents();
    }

    private void initializeComponents() {
        frame = new JFrame("朋友信息管理");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);

        tabbedPane = new JTabbedPane();
        frame.add(tabbedPane);

        mainPanel = new MainPanel();
        AddPanel addPanel = new AddPanel();
        SearchPanel searchPanel = new SearchPanel();
        UpdatePanel updatePanel = new UpdatePanel();
        DeletePanel deletePanel = new DeletePanel();

        tabbedPane.addTab("主界面", mainPanel);
        tabbedPane.addTab("添加", addPanel);
        tabbedPane.addTab("查询", searchPanel);
        tabbedPane.addTab("更新", updatePanel);
        tabbedPane.addTab("删除", deletePanel);

        displayFriends();

        frame.setVisible(true);
    }

    public static void refreshFriendsList() {
        mainPanel.remove(1);
        displayFriends();
    }

    static void displayFriends() {
        List<String> friendsInfo = new ArrayList<>();
        try (Connection conn = FriendDAO.getConnection()) {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM friends");

            while (rs.next()) {
                Friend friend = new Friend(rs.getInt("id"), rs.getString("name"), rs.getString("gender").charAt(0),
                        rs.getInt("age"), rs.getInt("favorability"), rs.getString("evaluation"));
                friendsInfo.add(friend.toString());
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        mainPanel.friendsList.setText("");
        for (String info : friendsInfo) {
            mainPanel.friendsList.append(info + "\n");
        }
    }

    public static void main(String[] args) {
        new FriendGUI();
    }
}